<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="stylesheet" href="/filetrans/css/style.css">
    <style>
        .error-message {
            color: red;
            font-size: 0.8em;
            margin-top: 5px;
        }

        input.error {
            border: 1px solid red;
        }
    </style>
</head>
<body>
<div th:if="${param.logout}" class="alert alert-success">
    您已成功退出系统
</div>
<div class="auth-container">
    <h1>注册</h1>
    <form id="registerForm" th:action="@{/filetrans/auth/register}" method="post" onsubmit="return validateForm(event)">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" required
                   minlength="3" maxlength="20"
                   oninput="validateUsername()"
            >
            <div id="usernameError" class="error-message"></div>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" required
                   oninput="validatePassword()">
            <div id="passwordError" class="error-message"></div>
        </div>
        <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input type="password" id="confirmPassword" name="confirmPassword" required
                   oninput="validatePassword()">
            <div id="confirmPasswordError" class="error-message"></div>
        </div>
        <button type="submit">注册</button>
        <p>已有账号？<a href="/filetrans/login">登录</a></p>
    </form>
</div>
<script src="/filetrans/js/md5.min.js"></script>
<script>

    function validateUsername() {
        const username = document.getElementById('username');
        const errorElement = document.getElementById('usernameError');
        const usernameValue = username.value.trim();

        if (usernameValue.length < 3 || usernameValue.length > 20) {
            username.classList.add('error');
            errorElement.textContent = '用户名长度必须在3到20个字符之间';
            return false;
        } else {
            username.classList.remove('error');
            errorElement.textContent = '';
            return true;
        }
    }

    function validatePassword() {
        const password = document.getElementById('password');
        const confirmPassword = document.getElementById('confirmPassword');
        const passwordError = document.getElementById('passwordError');
        const confirmPasswordError = document.getElementById('confirmPasswordError');
        let isValid = true;

        // 验证密码长度（可选）
        if (password.value.length < 6) {
            password.classList.add('error');
            passwordError.textContent = '密码长度至少6个字符';
            isValid = false;
        } else {
            password.classList.remove('error');
            passwordError.textContent = '';
        }

        // 验证密码匹配
        if (password.value !== confirmPassword.value) {
            confirmPassword.classList.add('error');
            confirmPasswordError.textContent = '密码不匹配';
            isValid = false;
        } else {
            confirmPassword.classList.remove('error');
            confirmPasswordError.textContent = '';
        }

        return isValid;
    }

    async function validateForm(event) {
        // 阻止表单默认提交行为
        event.preventDefault();

        // 验证用户名格式
        const isUsernameValid = validateUsername();
        // 验证密码格式和匹配
        const isPasswordValid = validatePassword();
        const username = document.getElementById('username').value.trim();

        // 格式验证失败则直接返回
        if (!isUsernameValid) {
            document.getElementById('username').focus();
            return false;
        }

        if (!isPasswordValid) {
            if (document.getElementById('password').value.length < 6) {
                document.getElementById('password').focus();
            } else {
                document.getElementById('confirmPassword').focus();
            }
            return false;
        }

        try {
            // 检查用户名是否存在
            const response = await fetch(`/auth/userExist/${username}`);
            const data = await response.text(); // 假设后端返回纯文本

            if (data === '用户存在') {
                document.getElementById('usernameError').textContent = '用户名已存在';
                document.getElementById('username').classList.add('error');
                document.getElementById('username').focus();
                return false;
            } else {
                // 用户名可用，处理密码加密并提交表单
                const passwordInput = document.getElementById('password');
                const encryptedPassword = md5(passwordInput.value);

                // 创建隐藏字段替换明文密码
                const hiddenPassword = document.createElement('input');
                hiddenPassword.type = 'hidden';
                hiddenPassword.name = 'password';
                hiddenPassword.value = encryptedPassword;

                // 移除原始密码字段
                passwordInput.remove();

                // 添加加密后的密码字段
                event.target.appendChild(hiddenPassword);

                // 手动提交表单
                event.target.submit();
            }
        } catch (error) {
            console.error('验证用户名时出错:', error);
            document.getElementById('usernameError').textContent = '验证用户名时出错，请重试';
            document.getElementById('username').classList.add('error');
            return false;
        }
    }
</script>
</body>
</html>